#include "io/console_writer.hpp"
#include <cstdio>
#include <cstring>

#ifdef _WIN32
#include <windows.h>
#endif

namespace axon_logger {
namespace io {

ConsoleWriter::ConsoleWriter() {
#ifdef _WIN32
    m_stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO info;
    if (GetConsoleScreenBufferInfo(m_stdout_handle, &info)) {
        m_default_colors = info.wAttributes;
    } 
#endif   
}

void ConsoleWriter::write(LogLevel level, std::string_view message) {
    std::lock_guard<std::mutex> lock(m_mutex);
    set_color(level);
    fwrite(message.data(), sizeof(char), message.length(), stdout);
    fputc('\n', stdout);
    reset_color();
    fflush(stdout);  // 立即显示
}


#ifdef _WIN32
void ConsoleWriter::set_color(LogLevel level) {
    unsigned short color = m_default_colors;
    switch (level) {
        case LogLevel::Trace:    color = 8; break; // 深灰色
        case LogLevel::Debug:    color = FOREGROUND_BLUE | FOREGROUND_GREEN; break; // 青色
        case LogLevel::Info:     color = m_default_colors; break; // 默认颜色
        case LogLevel::Warn:     color = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY; break; // 亮黄色
        case LogLevel::Error:    color = FOREGROUND_RED | FOREGROUND_INTENSITY; break; // 亮红色
        case LogLevel::Critical: color = BACKGROUND_RED | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY; break; // 红底亮白字
        default: break;
    }
    SetConsoleTextAttribute(m_stdout_handle, color);
}


void ConsoleWriter::reset_color() {
    SetConsoleTextAttribute(m_stdout_handle, m_default_colors);
}

#else // For Linux, macOS
void ConsoleWriter::set_color(LogLevel level) {
    const char* color_str = "";
    switch (level) {
        case LogLevel::Trace:    color_str = "\033[90m"; break;    // 亮黑（灰色）
        case LogLevel::Debug:    color_str = "\033[36m"; break;    // 青色
        case LogLevel::Info:     color_str = "\033[0m"; break;     // 默认/重置
        case LogLevel::Warn:     color_str = "\033[1;33m"; break;  // 亮黄色
        case LogLevel::Error:    color_str = "\033[1;31m"; break;  // 亮红色
        case LogLevel::Critical: color_str = "\033[1;37;41m"; break; // 亮白 on Red
        default: break;
    }
    fwrite(color_str, sizeof(char), strlen(color_str), stdout);
}

void ConsoleWriter::reset_color() {
    const char* color_str = "\033[0m"; // 重置所有属性
    fwrite(color_str, sizeof(char), strlen(color_str), stdout);
}
#endif

} // namespace io
} // namespace axon_logger
